package com.yunc.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunc.common.oauth2.TokenGenerator;
import com.yunc.common.utils.R;
import com.yunc.modules.sys.entity.SysUser;
import com.yunc.modules.sys.entity.SysUserToken;
import com.yunc.modules.sys.mapper.SysUserTokenMapper;
import com.yunc.modules.sys.service.ISysUserService;
import com.yunc.modules.sys.service.ISysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author taocongcong
 * @create 2017-12-15 13:46
 */
@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenMapper,SysUserToken> implements ISysUserTokenService {

    @Autowired
    private SysUserTokenMapper sysUserTokenMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 12小时后过期
     */
    private final static int EXPIRE = 3600 * 12;

    @Override
    public R insertToken(Long userId) {
        // 生成一个token
        String token = TokenGenerator.generateValue();
        // 当前时间
        Date now = new Date();
        // 过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);
        // 判断是否生成过token
        SysUserToken tokenEntity = sysUserTokenMapper.selectById(userId);
        if(tokenEntity == null){
            tokenEntity = new SysUserToken();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //保存token
            sysUserTokenMapper.insert(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            //更新token
            updateById(tokenEntity);
        }
        SysUser sysUser = sysUserService.getById(userId);
        return R.ok().put("token", token).put("user", sysUser);
    }
}
